package com.starblink.web

import android.graphics.Color
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.lifecycle.viewModelScope
import androidx.viewbinding.ViewBinding
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.base.activity.BaseTVMActivity
import com.starblink.android.basic.databinding.AddVWishlistFailBinding
import com.starblink.android.basic.ext.click
import com.starblink.android.basic.ext.runOnUIThread
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.FollowStoreEvent
import com.starblink.android.basic.widget.CustomDialog
import com.starblink.android.basic.widget.LoadingDialogManager
import com.starblink.basic.log.SKLogger
import com.starblink.basic.route.RoutePage
import com.starblink.basic.style.title.OnTitleBarListener
import com.starblink.basic.style.title.TitleBar
import com.starblink.basic.util.CheckUtil
import com.starblink.basic.util.CommUtils
import com.starblink.library.widget.wishlist.WishlistAddBottomDialog
import com.starblink.library.widget.wishlist.WishlistToast.toastAddWishlist
import com.starblink.library.widget.wishlist.bean.BatchProductArrEntry
import com.starblink.share.view.ShareDialog
import com.starblink.share.view.utils.ShareTypeEnum
import com.starblink.share.view.utils.ShareUrlUtils
import com.starblink.android.basic.bridge.BridgeUtil
import com.starblink.web.core.GuangWebView
import com.starblink.web.util.GuangWebViewPool
import com.starblink.web.util.WebCacheUtil
import com.starblink.web.util.WebUtil

abstract class WebBaseActivity<T : ViewBinding,VM : BaseViewModel> : BaseTVMActivity<T, VM>() ,
    GuangWebView.WebJsI, GuangWebView.OnWebChangeListener{
    private val TAG="GuangWebView"

    val mWebView by lazy { GuangWebViewPool.getInstance().getWebView(this,mWebUrl) }
    private var ifNeedClearCache=false //是否需要清理缓存
    private var titleBar:TitleBar?=null
    private var viewGroup:ViewGroup?=null
    private var pbWebViewBar: WebViewProgressBar?=null
    private var mWebUrl:String=""
    private var mWebTitle:String?=""
    private var ifUseCache=true //是否使用缓存
    private var ifStrictMode=false //是否宽松模式

    fun initWebView(titleBar:TitleBar?=null,viewGroup:ViewGroup?=null,pbWebViewBar: WebViewProgressBar?=null,mWebUrl:String="",mWebTitle:String?=null,ifUseCache:Boolean=true,ifStrictMode:Boolean=false){
        this.titleBar=titleBar
        this.viewGroup=viewGroup

        //不接收顶部进度条隐藏 接收则显示
//        this.pbWebViewBar=pbWebViewBar

        this.mWebUrl=mWebUrl
        this.mWebTitle=mWebTitle
        this.ifUseCache=ifUseCache
        this.ifStrictMode=ifStrictMode

        if(CheckUtil.isEmpty(this.mWebUrl)){
            return
        }
        initTitles()
        initWeb()
    }

    private fun initTitles() {
        titleBar?.let {

            if(WebUtil.isGuangUrl(mWebUrl)){
                //自己的H5地址默认隐藏标题栏
                it.visibility = View.GONE
                return
            }

            if(!CheckUtil.isEmpty(CommUtils.getUrlParma(mWebUrl, RoutePage.Web.PARAMS_APP_TITLE))){
                //链接中标题不为空
                mWebTitle= CommUtils.getUrlParma(mWebUrl, RoutePage.Web.PARAMS_APP_TITLE)
            }
            //预先加载的web 需替换成记录的webPreTitle
            if(!CheckUtil.isEmpty(mWebView.getPreWebTitle())){
                mWebTitle=mWebView.getPreWebTitle()
            }
            it.title = mWebTitle
            if("0" == CommUtils.getUrlParma(mWebUrl, RoutePage.Web.PARAMS_APP_SHOWNAV)){
                it.visibility = View.GONE
            } else{
                it.visibility = View.VISIBLE
            }

            //返回按钮
            it.setOnTitleBarListener(object : OnTitleBarListener {
                override fun onLeftClick(titleBar: TitleBar?) {
                    clickBack()
                }
            })
        }
    }

    private fun initWeb() {
        if("1" == CommUtils.getUrlParma(mWebUrl, RoutePage.Web.PARAMS_APP_CLEAR)){
            //接收是否需要清理缓存 后续增加本地H5版本号判断
            ifNeedClearCache=true
        }
        if("0" == CommUtils.getUrlParma(mWebUrl, RoutePage.Web.PARAMS_APP_USECACHE)){
            //链接上判断是否使用缓存
            ifUseCache=false
        }
        val params = FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        viewGroup?.addView(mWebView,params)
        mWebView.setLifecycleOwner(this)
        mWebView.setWebJsI(this)
        mWebView.setOnWebChangeListener(this)
        mWebView.guangLoadUrl(mWebUrl,ifUseCache,ifStrictMode)
    }

    /**
     * 集成了系统的回退和网页的回退
     */
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK ) {
            clickBack()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    //物理返回或左上角返回按钮
    private fun clickBack(){
        if(mWebView.canGoBack()){
            mWebView.goBack()
            return
        }
        finish()
    }

    //start---GuangWebView.WebJsI
    //显示隐藏titleBar
    override fun showTitleBar(show:Boolean?){
        show?.let {
            runOnUIThread {
                if (it) {
                    titleBar?.visibility = View.VISIBLE
                } else {
                    titleBar?.visibility = View.GONE
                }
            }
        }
    }
    //设置状态栏主题深色或浅色
    override fun setStatusBarColor(dark:Boolean?){
        dark?.let {
            runOnUIThread {
                if(it){
                    setStatusBarColor(Color.BLACK)
                }else{
                    setStatusBarColor(Color.WHITE)
                }
            }
        }
    }
    //app分享功能
    override fun appShare(urlLink:String?){
        //根据urlLink获取ShareTypeEnum类型
        urlLink?.let {
            var shareTypeEnum: ShareTypeEnum = when {
                urlLink.contains(ShareUrlUtils().picPath) -> ShareTypeEnum.PIC_POST
                urlLink.contains(ShareUrlUtils().videoPath) -> ShareTypeEnum.VIDEO_POST
                urlLink.contains(ShareUrlUtils().tagPath) -> ShareTypeEnum.TOPIC
                urlLink.contains(ShareUrlUtils().personalHomeShare) -> ShareTypeEnum.PERSONAL_HOME_SHARE
                urlLink.contains(ShareUrlUtils().whishlistPath) -> ShareTypeEnum.WISHLIST_BOARDS_SHARE
                else -> ShareTypeEnum.PRODUCT
            }
            //shareTypeEnum 用户获取分享文案 默认ShareTypeEnum.PRODUCT是因为默认没有文案 同步iOS
            ShareDialog(
                this,
                urlLink,
                shareCome = shareTypeEnum){}.show(this.supportFragmentManager, "share")
        }
    }
    //数据刷新
    override fun updateStoreSubscribeState(storeId:String?,subOrNot:Int?){
        //刷新首页和订阅数据
        val followStoreEvent=FollowStoreEvent(storeId, subOrNot==1, null)
        FlowBus.with<FollowStoreEvent>(FlowConst.FOLLOW_STORE_EVENT)
            .post(viewModel.viewModelScope, followStoreEvent)
        //跨进程通信
        BridgeUtil.sendFlowBus(FlowConst.FOLLOW_STORE_EVENT,followStoreEvent)
    }

    //是否展示loading
    override fun showLoadingAnim(show:Boolean?){
        show?.let {
            runOnUIThread {
                if (it) {
                    LoadingDialogManager.get().showH5Loading(this)
                } else {
                    LoadingDialogManager.get().dismissLoading()
                }
            }
        }
    }

    //web回退或退出web容器
    override fun tryBack() {
        runOnUIThread {
            clickBack()
        }
    }
    //直接关闭web容器
    override fun closeH5() {
        finish()
    }

    //预先加载H5列表
    override fun accWebPages(webPages: List<String>?) {
        webPages?.let {
            runOnUIThread {
                WebCacheUtil.preLoadUrl(this, webPages)
            }
        }
    }

    override fun toastAddWish(productId: String) {
        toastAddWishlist(productId)
    }

    override fun addCollectedProductToBoard(productId: String?, type: Int, mainImg: String?) {
        WishlistAddBottomDialog.showAddListDialog(
            this,
            batchPros = arrayListOf(
                BatchProductArrEntry(
                    id = productId ?: "",
                    type = type,
                    url = mainImg ?: ""
                )
            )
        )
    }
    //未登录状态收藏超过10时弹框
    override fun addVWishlistFail(){
        runOnUIThread {
            val contentBinding =
                AddVWishlistFailBinding.inflate(
                    LayoutInflater.from(this),
                    null,
                    false
                )
            val subFailDialog =
                CustomDialog.Builder(this)
                    .create(contentBinding.root)
            subFailDialog.show()
            contentBinding.tryIt.click {
                subFailDialog.dismiss()
                com.starblink.android.basic.extension.navigation(path = RoutePage.Login.SING_IN)
            }
        }
    }
    //end---GuangWebView.WebJsI

    //start---GuangWebView.OnWebChangeListener
    override fun titleChange(title: String?) {
        SKLogger.d(TAG,"titleChange --- $title")
        if (!CheckUtil.isEmpty(title)) {
            titleBar?.title = title
        }
    }

    override fun progressChange(progress: Int) {
        var newProgress = progress
        if (newProgress == 100) {
            pbWebViewBar?.setProgress(100)
            CommUtils.getHandler()
                .postDelayed(
                    {
                        pbWebViewBar?.visibility = View.GONE
                    },
                    200
                )//0.2秒后隐藏进度条
        } else if (pbWebViewBar?.visibility == View.GONE) {
            pbWebViewBar?.visibility = View.VISIBLE
        }
        //设置初始进度10，这样会显得效果真一点，总不能从1开始吧
        if (newProgress < 10) {
            newProgress = 10
        }
        //不断更新进度
        pbWebViewBar?.setProgress(newProgress)
    }

    override fun onInnerLinkChecked() {

    }

    override fun onWebLoadError() {

    }

    override fun onWebLoadStart(url: String) {

    }

    override fun onWebLoadFinish(url: String?) {
        //当前加载的页面url是进来的mWeburl 需清理历史记录
        //链接无参数时结尾不是'/' 无法匹配 因为加载后会加上'/'
        if(mWebUrl == url) {
            mWebView.clearHistory() //清理历史记录
        }
    }

    override fun onWebLoadStatus(params: Map<String, String>) {

    }
    //end---GuangWebView.OnWebChangeListener

    override fun onDestroy() {
        super.onDestroy()
        if(ifNeedClearCache){
            //如需清理缓存
            mWebView.clearCache(true) //清空缓存
            mWebView.clearFormData()
        }
        showLoadingAnim(false) //解决未加载完关闭Actvitiy dialog还没隐藏
    }
}